<template>
  <div class="container">
    <el-dialog
      :title="dialog.dialogType == 'edit' ? '修改返货单' : '创建返货单'"
      :visible.sync="dialog.centerDialogVisible"
      width="90%"
      center
      @open="getData"
      :lock-scroll="true"
      @close="insideHideDialog"
    >
      <div class="top" v-if="dialog.dialogType != 'edit'">
        <el-select
          size="small"
          v-model="outer.value"
          style="width: 50%"
          multiple
          filterable
          remote
          center
          reserve-keyword
          placeholder="请输入商品"
          :remote-method="remoteMethod"
          :loading="outer.loading"
          @change="commodityChange(outer.value)"
        >
          <el-option
            v-for="item in outer.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          class="add"
          size="small"
          type="primary"
          icon="el-icon-circle-plus"
          @click="addShopping"
          >添加批次</el-button
        >
      </div>
      <el-table
        :data="formData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="goods_name"
          label="商品"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="code"
          label="批次编码"
          align="center"
        ></el-table-column>
        <!-- <el-table-column prop="stock_net_num" label="剩余库存" align="center"></el-table-column> -->
        <el-table-column label="返货单价" width="150px" align="center">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.inp_price"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="返货数量" width="150px" align="center">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.num"
              type="number"
              size="small"
              @input="modificationNum(scope)"
              placeholder="请输入内容"
            ></el-input>
            <!-- <el-input-number
              size="small"
              @change="modificationNum(scope)"
              :controls="false"
              v-model="scope.row.num"
            ></el-input-number>-->
          </template>
        </el-table-column>
        <el-table-column
          prop="qty"
          label="件数"
          align="center"
        ></el-table-column>

        <el-table-column label="选择供应商" width="200px" align="center">
          <template slot-scope="scope">
            <el-select
              size="small"
              v-model="scope.row.supplierName"
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              placeholder="请选择供应商"
              :remote-method="insideRemoteMethod"
              :loading="inside.loading"
              @change="getOptionId(scope)"
            >
              <el-option
                v-for="item in inside.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" width="160">
          <template slot-scope="scope">
            <el-input type="textarea" v-model="scope.row.notes"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="dialog.dialogType != 'edit'"
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleEdit(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// import { selectSupplierList } from "@/api/supplier/supplierList";
import { selectSupplierData } from "@/api/supplier/supplierList"; //供应商
import {
  selectSupplierGoodsBatch,
  addReturnBill,
  findReturnBill,
  editReturnBill
} from "@/api/returnGoods/superReturnGoods";

export default {
  props: {
    dialog: Object
  },
  data() {
    return {
      formData: [],
      insideList: [],
      commodityList: [],
      outer: {
        options: [],
        value: [],
        list: [],
        loading: false,
        id: ""
      },
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
        buy_order_id: ""
      }
    };
  },
  created() {},
  methods: {
    //获取修改数据
    getData() {
      let data = {
        page: 1,
        limit: 50
      };
      //获取商品列表
      selectSupplierGoodsBatch(data).then(res => {
        this.outer.options = res.data.goodslist.map(item => {
          return {
            value: `${item.id}`,
            label: `${item.goods_name}[${item.id}]{${item.whsename}}`
          };
        });
        this.commodityList = res.data.goodslist;
      });
      //获取供应商列表
      selectSupplierData(data).then(res => {
        this.inside.options = res.data.paginate.data.map(item => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}(${item.supplier_code})`,
            code: `${item.supplier_code}`
          };
        });
      });
      if (this.dialog.dialogType == "edit") {
        let datas = {
          id: this.dialog.id
        };
        findReturnBill(datas).then(res => {
          if (res.code == 0) {
            let qty = (
              parseFloat(res.data.info.return_num) /
              parseFloat(res.data.info.rk_spec)
            ).toFixed(4);
            this.formData.push({
              id: res.data.info.batch_id,
              code: res.data.info.batch_code,
              // goods_id: res.data.info.goods_id,
              goods_name: res.data.info.goods_name,
              erp_goods_id: res.data.info.erp_goods_id,
              erp_goods_code: res.data.info.erp_goods_code,
              inp_price: res.data.info.return_price,
              qty: qty,
              unit: res.data.info.unit,
              spec: res.data.info.spec,
              supplierName: res.data.info.suppliser_info.name,
              supplierId: res.data.info.suppliser_info.id,
              // is_agriculture: res.data.info.is_agriculture,
              num: res.data.info.return_num,
              nums: res.data.detail_info.stock_num,
              rk_spec: res.data.info.rk_spec,
              kind: res.data.info.type == 1 ? 70 : 0,
              notes: res.data.info.notes
            });
            if (res.data.info.return_num > res.data.detail_info.stock_num) {
              this.$message({
                type: "info",
                message: `此商品库存数量剩余${
                  res.data.detail_info.stock_num
                }，不能大于此数量`
              });
            }
            this.inside.value = res.data.info.suppliser_info.name;
            this.inside.id = res.data.info.suppliser_info.id;
          }
        });
      }
    },
    //获取供应商数据
    getSupplierList(query) {
      let data = {
        name: query,
        page: 1,
        limit: 100
      };
      this.inside.loading = true;
      selectSupplierData(data).then(res => {
        this.inside.list = res.data.paginate.data.map(item => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}(${item.supplier_code})`,
            code: `${item.supplier_code}`
          };
        });
        this.inside.loading = false;
        this.inside.options = this.inside.list.filter(item => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      });
    },
    //选择供应商获取ID
    getOptionId(scope) {
      scope.row.supplierId = scope.row.supplierName;
    },
    //获取商品列表
    getCommodityList(query) {
      let data = {
        goods_name: query,
        page: 1,
        limit: 100,
        supplier_id: this.inside.id
      };
      this.outer.loading = true;
      selectSupplierGoodsBatch(data).then(res => {
        this.outer.list = res.data.goodslist.map(item => {
          let kind = item.kind == 70 ? "(赠品)" : "";
          return {
            value: `${item.id}`,
            label: `${item.goods_name}[${item.id}]${kind}{${item.whsename}}`
          };
        });
        this.outer.loading = false;
        this.outer.options = res.data.goodslist.map(item => {
          let kind = item.kind == 70 ? "(赠品)" : "";
          return {
            value: `${item.id}`,
            label: `${item.goods_name}[${item.id}]${kind}{${item.whsename}}`
          };
        });
        this.commodityList = res.data.goodslist;
      });
    },
    //修改数量
    modificationNum(scope) {
      if (parseFloat(scope.row.num) > scope.row.nums) {
        scope.row.num = scope.row.nums;
        this.$message({
          type: "info",
          message: "不能大于商品库存数量"
        });
      }

      scope.row.qty = (
        parseFloat(scope.row.num) / parseFloat(scope.row.rk_spec)
      ).toFixed(4);
      this.$set(this.formData, scope.$index, scope.row);
    },
    // 删除
    handleEdit(scope) {
      let id = scope.row.id;
      this.formData.forEach((res, index) => {
        if (res.id == id) {
          this.formData.splice(index, 1);
        }
      });
      this.outer = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: ""
      };
      this.inside = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: "",
        buy_order_id: ""
      };
      this.getData();
    },
    //提交
    confirm() {
      if (this.formData.length > 0) {
        // if (this.inside.id != "") {
        // let bool = true;
        // this.formData.forEach((res) => {
        //   if (!res.num) {
        //     bool = false;
        //   }
        // });
        // if (bool) {
        let form = [];
        this.formData.forEach(res => {
          form.push({
            supplier_id: res.supplierId,
            goods_name: res.goods_name,
            erp_goods_id: res.erp_goods_id,
            erp_goods_code: res.erp_goods_code,
            return_num: res.num,
            return_price: res.inp_price,
            batch_id: res.id,
            batch_code: res.code,
            unit: res.unit,
            spec: res.spec,
            qty: res.qty,
            rk_spec: res.rk_spec,
            notes: res.notes
          });
        });
        let data = {
          bill: form
          // is_agriculture: this.formData[0].is_agriculture,
          // type: this.formData[0].kind == 70 ? 1 : 0,
          // is_normal:this.formData[0].is_normal
          // goods_id: this.formData[0].goods_id,
        };
        // console.log(data);
        // return;
        if (this.dialog.dialogType == "edit") {
          data.bill[0].id = this.dialog.id;
          editReturnBill(data)
            .then(res => {
              if (res.code == 0) {
                this.$message({
                  message: res.msg,
                  type: "success"
                });
                this.insideHideDialog();
                this.$emit("upData");
              } else {
                this.$message({
                  message: res.msg,
                  type: "error"
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          addReturnBill(data)
            .then(res => {
              if (res.code == 0) {
                this.$message({
                  message: res.msg,
                  type: "success"
                });
                this.insideHideDialog();
                this.$emit("upData");
              } else {
                this.$message({
                  message: res.msg,
                  type: "error"
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        }
        // } else {
        //   this.$message({
        //     message: "请填写返回数量",
        //     type: "error",
        //   });
        // }
        // } else {
        //   this.$message({
        //     message: "请选择供应商",
        //     type: "info",
        //   });
        // }
      } else {
        this.$message({
          message: "请添加商品",
          type: "info"
        });
      }
    },
    commodityChange(scope) {
      if (this.insideList.length > 0) {
        if (scope.length < this.insideList.length) {
          this.insideList.forEach((res, index) => {
            if (res.id != scope[index]) {
              this.insideList.splice(index, 1);
            }
          });
        } else {
          let commodity = this.commodityList.filter(res => {
            return res.id == scope[scope.length - 1];
          });
          let kind = commodity[0].kind == 70 ? "(赠品)" : "";
          commodity[0].num = commodity[0].stock_num;
          commodity[0].nums = commodity[0].stock_num;
          commodity[0].goods_name =
            commodity[0].goods_name +
            "[" +
            commodity[0].id +
            "]" +
            kind +
            "{" +
            commodity[0].whsename +
            "}";
          commodity[0].inp_price = commodity[0].price;
          commodity[0].qty = commodity[0].stock_qty;
          this.insideList.push(commodity[0]);
        }
      } else {
        let commodity = this.commodityList.filter(res => {
          return res.id == scope[0];
        });
        let kind = commodity[0].kind == 70 ? "(赠品)" : "";
        commodity[0].num = commodity[0].stock_num;
        commodity[0].nums = commodity[0].stock_num;
        commodity[0].goods_name =
          commodity[0].goods_name +
          "[" +
          commodity[0].id +
          "]" +
          kind +
          "{" +
          commodity[0].whsename +
          "}";
        commodity[0].inp_price = commodity[0].price;
        commodity[0].qty = commodity[0].stock_qty;
        this.insideList.push(commodity[0]);
      }
    },
    //添加商品
    addShopping() {
      if (this.outer.value.length == 0) {
        this.$message({
          message: "请选择商品",
          type: "info"
        });
      } else {
        let bool = false;
        this.formData.forEach(prop => {
          this.insideList.forEach(res => {
            if (prop.id == res.id) {
              bool = true;
            }
          });
        });
        if (bool) {
          this.$message({
            message: "该批次商品已添加",
            type: "info"
          });
        } else {
          this.insideList.forEach(res => {
            this.formData.push(res);
          });
          this.outer.value = [];
          this.insideList = [];
        }
      }
    },
    //搜索商品数据
    remoteMethod(query) {
      if (query !== "") {
        this.getCommodityList(query);
      } else {
        this.outer.options = [];
      }
    },
    //搜索供应商数据
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //取消
    cancel() {
      this.insideHideDialog();
    },

    // 取消方法
    insideHideDialog() {
      this.dialog.centerDialogVisible = false;
      this.formData = [];
      this.inside = {
        innerVisible: false,
        options: [],
        value: [],
        list: [],
        loading: false,
        id: "",
        buy_order_id: ""
      };
      this.outer = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: ""
      };
    }
  }
};
</script>
<style scoped>
.top {
  position: relative;
  /* height: 40px; */
}
.main {
  display: flex;
  justify-content: center;
}
.add {
  margin: 10px 0;
  margin-left: auto;
}
</style>
